package com.lichhao.system.web.controller;

import java.io.File;
import java.io.OutputStream;
//import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.lichhao.system.model.UploadForm;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

@Controller
public class UploadFormController implements HandlerExceptionResolver {

	@Autowired
	protected MongoTemplate mongoTemplate;

	@RequestMapping(value = "/downLoad/{folder}/{prefix}/{suffix}")
	public void downLoad(HttpServletResponse response,
			@PathVariable String folder, @PathVariable String prefix,
			@PathVariable String suffix) throws IOException {

		String fileName = prefix+"."+suffix;
		
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String(fileName.getBytes(), "iso8859-1"));

		OutputStream os = response.getOutputStream();
		GridFS gridFs = new GridFS(mongoTemplate.getDb(), folder);
		GridFSDBFile gridFSDBFile = gridFs.findOne(fileName);

		FileCopyUtils.copy(gridFSDBFile.getInputStream(), os);
		
		os.flush();
		os.close();
	}

	@RequestMapping(value = "/FileUploadForm", method = RequestMethod.GET)
	public String showForm(ModelMap model) {

		UploadForm form = new UploadForm();
		model.addAttribute("FORM", form);
		return "FileUploadForm";

	}

	@RequestMapping(value = "/FileUploadForm", method = RequestMethod.POST)
	public ModelAndView processForm(HttpServletRequest request,
			@ModelAttribute(value = "FORM") UploadForm form,
			BindingResult result) {

		if (!result.hasErrors()) {
			// FileOutputStream outputStream = null;
			// String filePath = System.getProperty("java.io.tmpdir") + "/"
			// + form.getFile().getOriginalFilename();
			//
			// try {
			// outputStream = new FileOutputStream(new File(filePath));
			// outputStream.write(form.getFile().getFileItem().get());
			// outputStream.close();
			//
			// } catch (Exception e) {
			// System.out.println("Error while saving file");
			// return "FileUploadForm";
			// }

			String realPath = request.getSession().getServletContext()
					.getRealPath("");
			
			CommonsMultipartFile file = form.getFile();

			String folder = "upload";
			String originalFilename = file.getOriginalFilename();
			// String actualFilename = "["+originalFilename+"]";

			try {

				// File dest = new File(realPath + "/upload/dest/"
				// + originalFilename);
				//
				// file.transferTo(dest);

				GridFS gridFs = new GridFS(mongoTemplate.getDb(), folder);
				GridFSInputFile gfsFile = gridFs.createFile(file.getFileItem()
						.getInputStream());

				gfsFile.setFilename(originalFilename);
				gfsFile.save();

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			String[] s = originalFilename.split("\\.");

			String prefix = s[0];
			String suffix = s.length == 1 ? "" : s[1];

			ModelAndView mav = new ModelAndView();
			mav.addObject("folder", folder);
			mav.addObject("prefix", prefix);
			mav.addObject("suffix", suffix);

			mav.setViewName("success");
			return mav;

		} else {

			ModelAndView mav = new ModelAndView();
			mav.setViewName("/FileUploadForm");
			return mav;
		}
	}

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception) {

		Map<Object, Object> model = new HashMap<Object, Object>();

		if (exception instanceof MaxUploadSizeExceededException) {
			model.put(
					"errors",
					"File size should be less then "
							+ ((MaxUploadSizeExceededException) exception)
									.getMaxUploadSize() + " Bytes.");
		} else {
			model.put("errors", "Unexpected error: " + exception.getMessage());
		}

		model.put("FORM", new UploadForm());
		return new ModelAndView("/FileUploadForm", (Map) model);

	}
}
